<?php

namespace app\api\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\User as ModelUser;

class User
{
    protected $userModel = null;

    public function __construct()
    {
        $this->userModel = new ModelUser();
    }

    public function userLogin($data)
    {
        // 判断验证码是否与redis中的相同
        $redisCode = cache(config('redis.prefix').$data['phone_number']);
        if (empty($redisCode) || $redisCode != $data['code']) {
            // throw new \think\Exception('没有这个验证码哦！');
        }

        // 首先判断该用户是否存在
        $user = $this->userModel->getUserByPhoneNumber($data['phone_number']);
        // 如果没有该用户就帮他创建，反之更新数据
        if (!$user) {
            $username = '214集中营' . $data['phone_number'];
            $userInfo = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => 1
            ];
            try {
                $this->userModel->save($userInfo);
                $userId = $this->userModel->id;
            } catch (\Exception $e) {
                throw new \think\Exception('数据库内部异常');
            }
        } else {
            // 更新用户数据
            $userId = $user->id;
            $username = $user->username;
            $updata = [
                'operate_user' => $username
            ];
            try {
                $this->userModel->updateUser($userId, $updata);
            } catch (\Exception $e) {
                throw new \think\Exception('数据库内部异常！');
            }
        }

        /**
         * 创建用户后或者更新数据后创建token值，并将token值和用户相关信息存入redis
         */
        $token = Str::getToken($data['phone_number']);
        $redisData = [
            'id' => $userId,
            'username' => $username
        ];

        $res = cache(config('redis.token_pre') . $token, $redisData, Time::userLoginExpiresTime($data['type']));

        return $res ? ['token' => $token,'username' => $username] : false;
    }

    // 获取用户基本信息
    public function getNoramlUserById($id)
    {
        $id = intval($id);
        $userResult = $this->userModel->getUserById($id);
        if (!$userResult || $userResult->status != 1) {
            return [];
        }

        return $userResult;
    }

    // 通过用户名获取用户基本信息
    public function getNormalUserByUserName($username)
    {
        if (empty($username)) {
            return false;
        }
        $user = $this->userModel->getUserByUserName($username);
        if (!$user || $user->status != 1) {
            return [];
        }
        return $user;
    }

    // 用户个人中心修改
    public function update($id, $data)
    {
        // 检查这个用户名是否存在
        $userResult = $this->getNormalUserByUserName($data['username']);
        if ($userResult && $userResult->id != $id) {
            throw new \think\Exception('该用户已存在请重新设置！');
        }

        // 通过id查看用户是否存在
        $byIdResult = $this->getNoramlUserById($id);
        if (!$byIdResult) {
            throw new \think\Exception('该用户不存在');
        }

        $updateData = [
            'username' => $data['username'],
            'sex' => $data['sex']
        ];

        // 将数据更新进数据库
        $updateResult = $this->userModel->updateUser($id, $updateData);
        return $updateResult;
    }
}
